package cn.com.bsoft.immunity.kotlin

import com.fasterxml.jackson.databind.JavaType
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.type.TypeFactory
import java.io.InputStream
import java.io.InputStreamReader
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty

fun objectMapper(): ObjectMapper {
    return ObjectMapper()
}
class JsonPropertyDelegate<in T : Any> : ReadOnlyProperty<T, String> {
    operator override fun getValue(thisRef: T, property: KProperty<*>): String {
        val json =  objectMapper().writeValueAsString(thisRef)
        return json
    }
}

val <T:Any> KClass<T>.listJavaType: JavaType get() {
    return TypeFactory.defaultInstance().constructCollectionLikeType(List::class.java,this.java)
}

val <T:Any> KClass<T>.javaType:JavaType get() {
    return TypeFactory.defaultInstance().constructType(this.java)
}

fun <T:Any> KClass<T>.parametricType(vararg javaType: JavaType):JavaType {
    return TypeFactory.defaultInstance().constructParametricType(this.java,*javaType)
}

val <T : Any> T.json: String by JsonPropertyDelegate()

fun <T> String.json2obj(javaType: JavaType):T{
    return objectMapper().readValue(this,javaType)
}
fun <T> InputStreamReader.json2obj(javaType: JavaType):T{
    return objectMapper().readValue(this,javaType)
}
fun <T> InputStream.json2obj(javaType: JavaType):T{
    return objectMapper().readValue(this,javaType)
}